﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;

namespace Tradex.Messaging {

    /// <summary>
    /// This is an internal queue used by the Port to actually store the messages it gets.
    /// </summary>
    class Queue {

        internal Queue () {
            _Queue = new Queue<Message>();
        }

        Queue<Message> _Queue;

        /// <summary>
        /// This method is used to enqueue a message into the queue.
        /// </summary>
        /// <param name="message"></param>
        internal void Enqueue(Message message) {
            lock (_Queue) {
                _Queue.Enqueue(message);
                System.Threading.Monitor.Pulse(_Queue);
            }
        }

        /// <summary>
        /// This methosd is used to remove a message from the queue. It optionally waits a number of milliseconds
        /// to get an available item.
        /// </summary>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        internal Message Dequeue (ushort Timeout = 0) {
            lock (_Queue) {
                if (_Queue.Count != 0) {
                    return _Queue.Dequeue();
                } else {
                    Monitor.Wait(_Queue, (int) Timeout);
                    if (_Queue.Count != 0) {
                        return _Queue.Dequeue();
                    }
                    return null;
                }
            }
        }

        internal int Count {
            get {
                lock (_Queue) {
                    return _Queue.Count;
                }
            }
        }

    }

}
